// src-tauri/src/reputation_system.rs
use std::collections::HashMap;
use std::time::{SystemTime, UNIX_EPOCH};

use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Clone)]
pub struct PeerReputation {
    pub peer_id: String,
    pub trust_score: f64,
    pub shared_files_count: u32,
    pub positive_feedback: u32,
    pub negative_feedback: u32,
    pub last_activity: u64,
}

pub struct ReputationSystem {
    peers: HashMap<String, PeerReputation>,
    min_trust_score: f64,
}

impl ReputationSystem {
    pub fn new() -> Self {
        Self {
            peers: HashMap::new(),
            min_trust_score: 0.5, // 最低信任分数
        }
    }
    
    pub fn should_accept_from_peer(&self, peer_id: &str) -> bool {
        match self.peers.get(peer_id) {
            Some(reputation) => reputation.trust_score >= self.min_trust_score,
            None => false, // 未知peer默认不信任
        }
    }
    
    pub fn update_reputation(&mut self, peer_id: &str, positive: bool) {
        let reputation = self.peers.entry(peer_id.to_string())
            .or_insert(PeerReputation {
                peer_id: peer_id.to_string(),
                trust_score: 0.3, // 初始信任分数
                shared_files_count: 0,
                positive_feedback: 0,
                negative_feedback: 0,
                last_activity: SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs(),
            });
        
        if positive {
            reputation.positive_feedback += 1;
            let trust_score = Self::calculate_trust_score_static(reputation);
            reputation.trust_score = trust_score;
        } else {
            reputation.negative_feedback += 1;
            reputation.trust_score = Self::calculate_trust_score_static(reputation);
        }
        
        reputation.last_activity = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
    }
    
    fn calculate_trust_score(&self, reputation: &PeerReputation) -> f64 {
        Self::calculate_trust_score_static(reputation)
    }
    
    fn calculate_trust_score_static(reputation: &PeerReputation) -> f64 {
        let total = reputation.positive_feedback + reputation.negative_feedback;
        if total == 0 {
            return 0.3;
        }
        
        let base_score = reputation.positive_feedback as f64 / total as f64;
        
        // 考虑活跃度因素
        let time_factor = Self::calculate_time_factor_static(reputation.last_activity);
     
        base_score * time_factor
    }
    
    /// 计算时间因子，根据最后活动时间来调整信任分数
    /// 活动时间越近，时间因子越接近 1.0；活动时间越久，时间因子越小
    fn calculate_time_factor(&self, last_activity: u64) -> f64 {
        Self::calculate_time_factor_static(last_activity)
    }
    
    fn calculate_time_factor_static(last_activity: u64) -> f64 {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        let inactive_seconds = now.saturating_sub(last_activity);
        
        // 假设超过 30 天（2592000 秒）不活动，时间因子降为 0.5
        // 不活动时间越短，时间因子越接近 1.0
        let max_inactive = 2592000;
        if inactive_seconds >= max_inactive {
            0.5
        } else {
            1.0 - (inactive_seconds as f64 / max_inactive as f64) * 0.5
        }
    }
}
   